package com.hulman.oms.job;

import com.hulman.oms.bean.ElectricReport;
import com.hulman.oms.bean.WaterReport;
import com.hulman.oms.service.ElectricReportService;
import com.hulman.oms.service.PatrolReportService;
import com.hulman.oms.service.ShifterReportService;
import com.hulman.oms.service.WaterReportService;
import com.hulman.oms.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Date;

/**
 * 报表生成
 */
@Component
@Slf4j
public class ReportJob
{
    @Autowired
    private ElectricReportService electricReportService;
    @Autowired
    private WaterReportService waterReportService;
    @Autowired
    private PatrolReportService patrolReportService;
    @Autowired
    private ShifterReportService shifterReportService;

    /**
     * 每周一早晨6点生成本周的用电周报
     */
    @Scheduled(cron = "0 0 6 ? * MON")
    public void generateElectricReport()
    {
        ElectricReport electricReport = new ElectricReport();
        log.info("生成用电周报");
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int week = now.get(WeekFields.ISO.weekOfWeekBasedYear());
        electricReport.setYear(year);
        electricReport.setWeek(week);
        electricReport.setStartDate(new Date());
        electricReport.setCreateTime(new Date());
        electricReport.setEndDate(DateUtil.addDays(new Date(), 6));
        electricReportService.createReport(electricReport);
    }

    /**
     * 每周一早晨6点生成本周的用电周报
     */
    @Scheduled(cron = "0 0 6 ? * MON")
    public void generateWaterReport()
    {
        WaterReport waterReport = new WaterReport();
        log.info("生成用水周报");
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int week = now.get(WeekFields.ISO.weekOfWeekBasedYear());
        waterReport.setYear(year);
        waterReport.setWeek(week);
        waterReport.setStartDate(new Date());
        waterReport.setCreateTime(new Date());
        waterReport.setEndDate(DateUtil.addDays(new Date(), 6));
        waterReportService.createReport(waterReport);
    }


    /**
     * 每天8点生成巡检日报
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void generatePatrolReport()
    {
        Date yesterday = DateUtil.addDays(new Date(), -1);
        try
        {
            patrolReportService.createPatrolReport(yesterday);
        } catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 每天8点生成当班值班长日报
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void generateShifterReport()
    {
        shifterReportService.createTodayShifterReport();
    }
}
